package com.heima.gateway.ruotes;

import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.stereotype.Component;
import org.springframework.util.RouteMatcher;
import reactor.core.publisher.Mono;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;

@Slf4j
@Component
@RequiredArgsConstructor
public class DynamicRouteLoader2 {
    private final NacosConfigManager nacosConfigManager;
    private final RouteDefinitionWriter writer;
    private String dataId = "hm-gateway-routes.json";
    private String group = "DEFAULT_GROUP";
    private Set<String> routeIds = new HashSet<>();

    public void initRouteConfigListener() throws Exception {
        String routeConfig = nacosConfigManager.getConfigService().getConfigAndSignListener(dataId, group, 5000, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String routeConfig) {
                updateRouteConfig(routeConfig);

            }
        });

        updateRouteConfig(routeConfig);
    }

    public void updateRouteConfig(String routeConfig) {
        List<RouteDefinition> routes = JSONUtil.toList(routeConfig, RouteDefinition.class);
        for (String routeId : routeIds) {
            writer.delete(Mono.just(routeId)).subscribe();
        }
        routeIds.clear();
        for (RouteDefinition route : routes) {
            writer.save(Mono.just(route)).subscribe();
            routeIds.add(route.getId());
        }
    }
}
